package com.shuhe.handler;

import com.alibaba.fastjson.JSONObject;
import com.shuhe.metastore.MetaMysql;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;

import static com.shuhe.common.CommonFunction.*;

public class CodeHandler extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection metaConn = null;
        try {
            req.setCharacterEncoding("UTF-8");
            resp = setResponse(resp);
            String bodyStr = readAsChars(req);
            JSONObject bodyJson = JSONObject.parseObject(bodyStr);
            String code82 = bodyJson.getString("code82");
            metaConn = MetaMysql.connect();
            ResultSet rs = MetaMysql.querySql(metaConn, "select * from my_code where code82 = '" + code82 + "'");
            if (rs.next()) {
                resp.getWriter().write("{" +
                        "    \"code\": \"1\"" +
                        "}");
            } else {
                String sql = "insert into my_code(code82) values('" + code82 + "')";
                MetaMysql.execSql(metaConn, sql);
                resp.getWriter().write("{" +
                        "    \"code\": \"0\"," +
                        "    \"data\": \"" + code82 + "\"" +
                        "}");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            closeDb(metaConn);

        }
    }
}
